package com.schoolET.service.admin.adminImpl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolET.config.OssConfig;
import com.schoolET.entity.Goods;
import com.schoolET.entity.OrderManagement;
import com.schoolET.entity.vo.InquireGoodsVO;
import com.schoolET.error.costom.GoodsEditException;
import com.schoolET.mapper.GoodsMapper;
import com.schoolET.mapper.OrderManagementMapper;
import com.schoolET.service.admin.IGoodsManageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author lin
 * @since 2024-05-31
 */
@Service
public class GoodsManageServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsManageService {

    @Resource
    private OrderManagementMapper orderManagementMapper;

    @Resource
    private OssConfig ossConfig;

    @Override
    public Page<Goods> inquireGoods(InquireGoodsVO inquireGoodsVO) {
        if (inquireGoodsVO.getPageNum() == null || inquireGoodsVO.getPageSize() == null) {
            inquireGoodsVO.setPageNum(1);
            inquireGoodsVO.setPageSize(5);
        }
        Page<Goods> page = new Page<>(inquireGoodsVO.getPageNum(), inquireGoodsVO.getPageSize());
        return baseMapper.selectByPositionAndTypeAndTheme(page, inquireGoodsVO);
    }

    @Override
    @Transactional
    public boolean goodsCg(Goods goods, MultipartFile file) throws IOException {
        OrderManagement orderManagement = orderManagementMapper.selectByGoodsId(goods.getId());
        if (orderManagement.getTradingStatus() != 1) {
            throw new GoodsEditException();
        }
        Goods goods1 = baseMapper.selectById(goods.getId());
        String path = ossConfig.putObject(file, "goods");
        goods.setPicture(path);
        System.out.println(goods);
        baseMapper.updateById(goods);
        ossConfig.getOSSClient().deleteObject(ossConfig.getBucketName(), goods1.getPicture());
        return true;
    }

    @Override
    @Transactional
    public boolean goodsDel(Integer id) {
        OrderManagement orderManagement = orderManagementMapper.selectByGoodsId(id);
        if (orderManagement.getTradingStatus() != 1) {
            throw new GoodsEditException();
        }
        baseMapper.deleteById(id);
        orderManagementMapper.deleteById(orderManagement.getId());
        return true;
    }
}
